package com.zm.demo.netty.client.count;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CountClient {
    ExecutorService executorService = Executors.newFixedThreadPool(50);
    public static void main(String[] args) throws Exception{
        new CountClient().start();
    }

    public void start()throws Exception{
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress("127.0.0.1", 9999))
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
//                                .addLast(new CountClientHandler())
                                .addLast(new CountClientReceiveHandler())
                        ;
                    }
                });
        try {
            for (int i = 0; i < 100 ; i++) {
                Future<Throwable> cause = executorService.submit(() ->{
                    try {
                        ChannelFuture channelFuture = bootstrap.connect().sync();
                        channelFuture.channel().closeFuture().sync();
                        return null;
                    } catch (Exception e){
                        return e;
                    }
                });
                if (cause.get() != null){
                    throw cause.get();
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            executorService.shutdown();
            eventLoopGroup.shutdownGracefully().sync();
        }

    }
}
